package com.defangit.award.extend.wxmp.orm;

import com.defangit.award.extend.wxmp.WxmpPluginEntry;
import com.defangit.award.extend.wxmp.domain.WxmpUser;
import com.defangit.openapis.wechat.mp.Wechat;
import com.defangit.openapis.wechat.mp.WechatMapper;
import com.defangit.openapis.wechat.mp.user.domain.UserInfo;
import laogen.hibernate.CommonService;
import laogen.util.StringUtil;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.Path;

/**
 * Created by zhangfagen on 2019/1/10.
 */
public class WxmpUserService extends CommonService<WxmpUser> {
    private static Logger logger= LoggerFactory.getLogger(WxmpUserService.class);
    public boolean addUser(String openId, String gh,int userid){
        return addUser(openId,gh,userid,null,null);
    }
    public boolean addUser(String openId, String gh,int userid,String name,String mobile){
        WxmpUser user=(WxmpUser)forAll().add(Restrictions.eq("info.openid",openId))
                .uniqueResult();
        //todo 尝试解决微信昵称mojo表情
        if(user==null){
            getSession().createSQLQuery("set names utf8mb4").executeUpdate();
            UserInfo info= WxmpPluginEntry.getWechat(gh).getUserManager().user(openId);
            logger.error(WechatMapper.getInstance().writeValue(info));
            if(StringUtil.notEmpty(info.getOpenid())){
                getSession().save(info);
                user=new WxmpUser().setInfo(info);
            }else{
                return false;
            }
        }
        if(StringUtil.notEmpty(user.getInfo().getOpenid())) {
            update(user.setMobile(mobile).setRealName(name).setUserId(userid));
            commitSession();
        }else{
            return false;
        }
        return true;
    }
}
